import request from '../request.ts'

/**
 * 按树形菜单格式化要输出的数据
 * @param tree 数组 需要格式化的数据
 * @param dataKey 元素的唯一值名称，例如id
 * @param parentKey 父元素唯一值名称，例如parentId
 * @param parentValue 树起点格式化的值
 */

function formatTree(tree:Array<object>, dataKey:String, parentKey:String, parentValue:String){
    let result:Array<object> = []
    for(let i in tree){
        let child:object = tree[i]
        // @ts-ignore
        if (child[parentKey] == parentValue){
            result.push(child)
            // @ts-ignore
            let children = formatTree(tree, 'deptId', 'parentId', child[dataKey])
            if (children.length>0){
                // @ts-ignore
                child.children = children
            }
        }
    }

    return result
}
//获取菜单资源
export const getDeptList = async  (search:Object) => {
    let r:any = await request({
        url: '/system/dept/list',
        method: 'get',
        loading: true,
        data:search
    })
    let data = formatTree(r.data.rows,'deptId', 'parentId', "0")
    // console.log(data.length === 0 , tree.length>0)
    if (data.length === 0 && r.data.length>0){
        data = formatTree(r.data, 'deptId', 'parentId', r.data[0].parentId)
    }
    return {
        data:data,
        total:r.data.length
    }
}
//获取部门结构
export const getDeptTree = async  () => {
    let r:any = await request({
        url: '/system/user/deptTree',
        method: 'get',
        loading: true
    })
    return r.data
}

//新增菜单资源 /system/menu
export const addDept = async  (data:Object) => {
    let r:any = await request({
        url: '/system/dept/edit',
        method: 'post',
        loading: true,
        data:data
    })
    return r
}
//修改菜单资源 /system/menu
export const editDept = async  (data:Object) => {
    let r:any = await request({
        url: '/system/dept/edit',
        method: 'put',
        loading: true,
        data:data
    })
    return r
}
//删除
export const delDept = async  (id:Number) => {
    let r:any = await request({
        url: '/system/dept/delete',
        method: 'delete',
        loading: true,
        data:{
            deptId:id
        }
    })
    return r
}